package com.gzh.system.mq;

import com.gzh.core.util.StringUtils;
import com.gzh.system.config.RabbitMQConfig;
import com.gzh.system.service.MailService;
import com.gzh.system.service.dto.RemindInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;

@Component
@Slf4j
//@RabbitListener(queues = {RabbitMQConfig.RABBITMQ_DEMO_TOPIC})
//使用queuesToDeclare属性，如果不存在则会创建队列
@RabbitListener(queuesToDeclare = @Queue(RabbitMQConfig.RABBITMQ_TOPIC))
public class RabbitDemoConsumer {

    @Value("${config.mail.username}")
    private String username;

    @Autowired
    private MailService mailService;

    @RabbitHandler
    public void process(Map map){
        RemindInfo msg = (RemindInfo) map.get("msg");
        Transport ts = null;
        try {
            Session session = mailService.getSession();
            ts = session.getTransport();
            // 连接邮件服务器：邮箱类型，帐号，POP3/SMTP协议授权码 163使用：smtp.163.com
            ts = mailService.getTransport(ts);
            // 创建邮件
            Message message = createMail(session, msg);
            // 发送邮件
            ts.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            log.error("发送邮件失败",e);
        }finally {
            if (ts != null) {
                try {
                    ts.close();
                } catch (MessagingException e) {
                    log.error("Transport关闭失败", e);
                }
            }
        }
    }

    private Message createMail(Session session, RemindInfo msg) throws Exception {
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress(username));
        // 指明邮件的收件人，发件人和收件人如果是一样的，那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(msg.getMail()));
        // 邮件的标题
        message.setSubject("作业提醒");
        // 邮件的文本内容
        String courseName = msg.getCourseName();
        String workName = msg.getWorkName();
        Integer endTime = msg.getEndTime();
        Integer endDate = msg.getEndDate();
        message.setContent(  "课程:" + courseName +
                "<br/>作业:" +workName + "<br/>"
                + "将在" + StringUtils.formatTime(endDate,endTime) + "截止,请及时完成<br/>"
                + "请勿回复此邮箱", "text/html;charset=UTF-8");
        // 返回创建好的邮件对象
        return message;
    }
}
